﻿Create Procedure [dbo].[accounts_registration_delete]
-- --------------------------------------------------------------------------------- 
-- Procedure Name: accounts_registration_delete
--
-- Description: Deletes registration requests
--
--
--
-- Version  Date          Author           Description
-- ---------------------------------------------------------------------------------
--  1       13-Apr-2012   The Collective   Created procedure
-- 
--
--
--
-- ---------------------------------------------------------------------------------
-- ---------------------------------------------------------------------------------
(@UserGUIDListXml as xml, 
 @SecurityCurrentUsername as varchar(255),
 @returncode as int output,
 @returnmessage as varchar(200) output )
AS
BEGIN

    set nocount on

	-- Declarations
    Declare @SecurityCurrentUserGuid Uniqueidentifier;
	Declare @UserGUIDtoDelete Uniqueidentifier;
	Declare @UserGUIDList as Guid_DT;
	Declare @recordcount as int;
	   

    -- Initialise variables
    Set @returncode = 0;
    Set @returnmessage = '';
	Set @recordcount = 0;

    -- Get the guid for the username of the logged in user
    Select @SecurityCurrentUserGuid = User_GUID from Accounts_User where username = @SecurityCurrentUsername;
    
    -- Check that the current user is admin
    If not exists(Select user_GUID from Accounts_User_Roles where User_GUID =  @SecurityCurrentUserGuid and RoleNumber = 101)
       Begin
          -- Exit if user does not have permission
          Set @returncode = 1;
          Set @returnmessage = 'Error. Logged in user is not an administrator';
	      Return 1;
       End;
    
	-- Copy the xml data to table variable
	insert into @UserGUIDList 
    select tab.col.value('@GuidID','uniqueidentifier') from @UserGUIDListXml.nodes('/processlist/regrequest') as tab(col);
	
	-- Declare the processing cursor
	Declare RegCursor cursor for select GuidID FROM @UserGUIDList;

	-- Open the cursor
    open RegCursor;
    fetch next from RegCursor into @UserGUIDtoDelete;
    while @@FETCH_STATUS = 0	
	begin
                        
	    -- Remove the registration request
	   Delete from Accounts_Registration_Requests where User_GUID = @UserGUIDtoDelete;

	   -- Add number of rows affected to the record counter
	   set @recordcount = @recordcount + @@rowcount;
        
       -- Fetch the next record
	   fetch next from RegCursor into @UserGUIDtoDelete;

  	end;  -- while loop

	-- Close the cursor
	close RegCursor;
	deallocate RegCursor;

	Set @returnmessage = CAST(@recordcount AS varchar(5)) + ' records were deleted.';

    set nocount off
    
    Return 0;

END;